package com.github.cakin.shiro.chapter24.web.controller;

import com.github.cakin.shiro.chapter24.Constants;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Collection;

/**
 * @className: SessionController
 * @description: 会话控制器
 * @date: 2020/5/31
 * @author: cakin
 */
@RequiresPermissions("session:*")
@Controller
@RequestMapping("/sessions")
public class SessionController {
    /**
     * sessionDAO
     */
    @Autowired
    private SessionDAO sessionDAO;

    /**
     * 功能描述：提供了展示所有在线会话列表，通过 sessionDAO.getActiveSessions() 获取所有在线的会话
     *
     * @param model 展示给前端的数据
     * @return String 前端展示页
     * @author cakin
     * @date 2020/5/31
     */
    @RequestMapping()
    public String list( Model model ) {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        model.addAttribute("sessions", sessions);
        model.addAttribute("sessionCount", sessions.size());
        return "sessions/list";
    }

    /**
     * 功能描述：强制退出某一个会话
     *
     * @param sessionId sessionId
     * @param redirectAttributes 重定向属性
     * @return String 重定向页
     * @author cakin
     * @date 2020/5/31
     */
    @RequestMapping("/{sessionId}/forceLogout")
    public String forceLogout(
            @PathVariable("sessionId") String sessionId, RedirectAttributes redirectAttributes ) {
        try {
            Session session = sessionDAO.readSession(sessionId);
            if (session != null) {
                // 在指定会话中设置 Constants.SESSION_FORCE_LOGOUT_KEY 属性
                // ForceLogoutFilter 会判断并进行强制退出
                session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
            }
        } catch (Exception e) {
        }
        redirectAttributes.addFlashAttribute("msg", "强制退出成功！");
        return "redirect:/sessions";
    }
}
